import hashlib
import random

import icecream
import scrapy
from scrapy import cmdline
import logging
import time,math
from hashlib import md5

logging.getLogger('scrapy').propagate = False
times = str(math.ceil(time.time()*1000) + random.randint(1,10))
data = {
    'i': 'hello',
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'salt': times,
    'sign': "",
    'lts': times[:-1],
    'bv': '24ecb70ba6203e4453baed50aa26b78e',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTlME',
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
    'Referer': 'https://fanyi.youdao.com/',
    'Cookie': 'OUTFOX_SEARCH_USER_ID=1469094762@10.108.160.105; JSESSIONID=aaafTj2FQTWCcdVt5qjVx; OUTFOX_SEARCH_USER_ID_NCOO=719838735.5270045; ___rl__test__cookies={}'.format(data['sign'])
}

class AndySpider(scrapy.Spider):
    name = 'andy'
    # allowed_domains = ['www.youdao.com']
    # start_urls = ['https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule']
    key = '你好'
    def Md5(self,ff):
        self.md5 = hashlib.md5()
        self.md5.update(ff.encode('utf8'))
        return self.md5.hexdigest()

    def start_requests(self):
        sign = "fanyideskweb" + self.key + times + "Y2FYu%TNSbMCxc3t2u^XT"
        data['i'] = self.key
        data['sign'] = self.Md5(sign)
        icecream.ic(data)
        url = 'https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
        # FormRequest 使用POST方法提交数据
        yield scrapy.FormRequest(url=url,headers = headers,formdata = data,callback = self.parse)


    def parse(self, response):
        res = response.json()
        result = res.get('translateResult')[0][0]['tgt']
        icecream.ic(result)


if __name__ == '__main__':
    cmdline.execute('scrapy crawl andy'.split())
